<?php
namespace app\interfaces\controller;

use app\interfaces\model\MerchantOrder as OrderModel;
use app\interfaces\model\Express as ExpressModel;
use app\interfaces\model\MemberRefund as MemberRefundModel;
use app\interfaces\model\Member as MemberModel;
use app\interfaces\model\MemberOrderAttached as MemberOrderAttachedModel;
use think\Cache;
use think\Db;
use think\Request;
use think\Exception;

class MerchantOrder
{

    /*
     * 商家端 - 订单管理
     * @param  string $shop_id  店铺ID
     * @param  string $status   订单状态
     */
    public function order_list()
    {

        // 获取参数
        $shop_id = Request::instance()->param('shop_id');
        $status = Request::instance()->param('status', 'all');
        $order_number = Request::instance()->param('order_number');

        if (empty($shop_id)) throw new Exception('not Empty');

        // 搜索条件
        $condition['shop_id'] = ['eq', $shop_id];

        // 条件
        if ($status <> 'all') $condition['status'] = [['in', $status], ['not in', '4,8']];
        if ($status == 'all') $condition['status'] = [['egt', '0'], ['not in', '4,8']];
        if (!empty($order_number)) $condition['shop_order_number'] = ['eq', $order_number];

        $model = new OrderModel();

        $result = $model->where($condition)
            ->field('id,create_time,price,status,express_number,express_value,shop_order_number,update_time as refund_status,update_time as refund_type')
            ->relation('goods')
            ->order('create_time','desc')
            ->paginate(6)
            ->toArray();

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 商家端 - 订单详情
     * @param  string $shop_id   店铺ID
     * @param  string $order_id  订单ID
     */
    public function order_view()
    {

        // 获取参数
        $shop_id = Request::instance()->param('shop_id');
        $order_id = Request::instance()->param('order_id');

        if (empty($shop_id) || empty($order_id)) throw new Exception('not Empty');

        $model = new OrderModel();

        $result = $model->where(['shop_id' => $shop_id, 'id' => $order_id])
            ->field('member_id,address_name,address_phone,address_area,address_site,shop_order_number,message,price,freight,status,create_time')
            ->find();

        // 读取用户信息
        $member = MemberModel::where(['id' => $result['member_id']])->field('username,nickname')->find();

        if (empty($member['nickname'])) {
            $member['nickname'] = substr_replace($member['username'], '****', 3, 4);
        }

        $result['buyer'] = $member['nickname'];

        $result['refund_status'] = (int)Db::name('member_refund')->where(['order_number' => $result['shop_order_number']])->value('status');

        $result['goods'] = MemberOrderAttachedModel::where(['order_id' => $order_id])
            ->field('goods_id,attr,number,price,title,thumb_img,rebate_percentage')
            ->select();

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 商家端 - 修改订单
     * @param  string $shop_id      店铺ID
     * @param  string $order_id     订单ID
     */
    public function update_order()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '提交方式错误'];

        // 获取参数
        $shop_id = Request::instance()->param('shop_id');
        $order_id = Request::instance()->param('order_id');
        $price = Request::instance()->param('price');

        if (empty($shop_id) || empty($order_id)) throw new Exception('not Empty');

        if ($price <= 0) return ['code' => 401, 'message' => '金额不能小于等于0'];

        $model = new OrderModel();

        $result = $model->where(['shop_id' => $shop_id, 'id' => $order_id])
            ->update(['price' => $price]);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 商家端 - 删除订单
     * @param  string $shop_id      店铺ID
     * @param  string $order_id     订单ID
     */
    public function delete_order()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '提交方式错误'];

        // 获取参数
        $shop_id = Request::instance()->param('shop_id');
        $order_id = Request::instance()->param('order_id');

        if (empty($shop_id) || empty($order_id)) throw new Exception('not Empty');

        $model = new OrderModel();

        $result = $model->where(['shop_id' => $shop_id, 'id' => $order_id])
            ->update(['status' => '8']);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 商家端 - 快递列表
     */
    public function express_list()
    {

        $result = ExpressModel::all();

        if ($result) {
            return ['code' => 200, 'message' => '成功', 'data' => $result];
        }

        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 商家端 - 订单发货
     * @param  string $shop_id      店铺ID
     * @param  string $order_id     订单ID
     */
    public function shipments_order()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '提交方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['shop_id']) || empty($data['order_id']) || empty($data['express_name']) || empty($data['express_number']) || empty($data['express_value'])) throw new Exception('not Empty');

        $data['status'] = '2';

        $model = new OrderModel();

        $result = $model->allowField(true)->save($data, ['id' => $data['order_id'], 'shop_id' => $data['shop_id']]);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 商家端 - 订单退款详情
     * @param  string $shop_id      店铺ID
     * @param  string $order_id     订单ID
     */
    public function refund_order_view()
    {

        // 获取参数
        $order_number = Request::instance()->param('order_number');

        if (empty($order_number)) throw new Exception('not Empty');

        $model = new MemberRefundModel();

        $result = $model->where(['order_number' => $order_number])
            ->field('id,order_number,type,cause,amount,explain,picArr,tracking_number,status,create_time,refund_time')
            ->find();

        $result['picArr'] = unserialize($result['picArr']);

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 商家端 - 订单退款快递详情
     * @param  string $order_number 订单号
     */
    public function tracking_view()
    {

        // 获取参数
        $order_number = Request::instance()->param('order_number');

        if (empty($order_number)) throw new Exception('not Empty');

        $model = new MemberRefundModel();

        $result = $model->where(['order_number' => $order_number])
            ->field('tracking,tracking_number,picArr')
            ->find();

        $result['picArr'] = unserialize($result['picArr']);

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 商家端 - 订单退款提交
     * @param  string $order_number      订单号
     * @param  string $status            订单状态
     */
    public function refund_order()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '提交方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['order_number']) || empty($data['status'])) throw new Exception('not Empty');

        if ($data['status'] == '1') {

            $information = [
                'status' => $data['status'],
                'price' => $data['price'],
                'refund_time' => time()
            ];

        } else {

            $information = [
                'status' => $data['status'],
                'message' => $data['message']
            ];

        }

        $model = new MemberRefundModel();

        $result = $model->where(['order_number' => $data['order_number']])->update($information);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];
    }

    /*
     * 用户端 - 物流详情
     * @param  string $express_number           快递单号
     * @param  string $express_value            快递参数
     */
    public function express_view()
    {
        // // 获取参数
        $express_number = Request::instance()->param('express_number');
        $express_value = Request::instance()->param('express_value');

        if (empty($express_value) || empty($express_number)) throw new Exception('not Empty');

        // 快递100
        $data['customer'] = Cache::get('web_express_customer');
        $data['param'] = json_encode(['com' => $express_value, 'num' => $express_number]);
        $data["sign"] = strtoupper(md5($data['param'] . Cache::get('web_express_key') . $data['customer']));

        $information = $this->express_post($data, Cache::get('web_express_url'));

        if (empty($information['com'])) return ['code' => 400, 'message' => '暂无记录'];

        $information['com'] = Db::name('express')->where(['code' => $information['com']])->value('name');

        return $information;

    }

    /*
     * 快递100 post_curl
     */
    protected function express_post($data, $url)
    {
        $o = "";
        foreach ($data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
        }
        // halt($o);
        $post_data = substr($o, 0, -1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //value为0表示直接输出结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $is_success = curl_exec($ch);
        curl_close($ch);
        return json_decode($is_success, true);
    }

}
